var fs = require('fs');
var path = require('path')
var sql = require('./sql')
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);

var bodyParser = require('body-parser');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var comment = require('./api/comment');
var file = require('./api/file')
var notice = require('./api/notice')
app.use(bodyParser.urlencoded({ extended: false }));

var onlineUsers = new Object();
var onlineCount = 0;


io.on('connection', function(socket) {
    console.log('a new join')
    socket.on('join', function(data) {
        onlineUsers[data.userid] = socket
        console.log('join from client')
    });
    socket.on('newNotices', function(data) {
        console.log('newNotices')
        if (onlineUsers[data.to]) {
            var sqlString = 'select n.*,t.taskcomments,p.projectname from notices n left join tasks t on (n.taskid = t.id) left join projects p on (n.projectid = p.id) where n.toPersonId = ' + data.to + ' and n.status = 1';
            sql.sequelize.query(sqlString).spread(function(results, metadata) {
                onlineUsers[data.to].emit('haveNewNotice', results)
            });
        }
    })
});

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", '*');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
//添加评论
app.post('/comment/addcomment', comment.addComment);
//删除评论
app.post('/comment/deletecomment', comment.deleteComment);
//根据taskid获取评论
app.post('/comment/getcomments', comment.getComments);

//测试上传类型
app.options('/file/upload', multipartMiddleware, file.upload)

app.post('/file/upload', multipartMiddleware, file.upload)

app.post('/file/updatefile', file.updateFile)

app.post('/file/getfile', file.getFile)

app.post('/file/deleteFile', file.deleteFile)

//添加提醒通知
app.post('/notice/addnotice', notice.addNotice)
    //修改通知状态
app.post('/notice/updateNotice', notice.updateNotice)
    //根据toPersonId获取通知
app.post('/notice/getNotices', notice.getNotices)

// app.listen(5001)
server.listen(5001);